package controller

import (
	"encoding/base64"
	"github.com/gin-gonic/gin"
	"wish_go/src/main/com/ajie/common"
	"wish_go/src/main/com/ajie/result"
)

// @Tags 生成验证码
// @Summary 创建uuid验证码唯一标识
// @accept json
// @Produce  json
// @Success 200 {object} result.Result
// @Failure 500 {object} result.Result
// @Router /captcha/create [GET]
func GenerateImg(req *gin.Context) {
	imgId := common.Instance().CreateImage()
	result.SuccessData(req, "二维码创建成功", imgId)
}

// @Tags 生成验证码
// @Summary 获得验证码base64编码
// @accept json
// @Produce  json
// @Param key path string true "uuid验证码唯一标识"
// @Success 200 {object} result.Result
// @Failure 500 {object} result.Result
// @Router /captcha/img [GET]
func GetCaptcha(req *gin.Context) {
	key := req.Param("key")
	req.Writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	req.Writer.Header().Set("Pragma", "no-cache")
	req.Writer.Header().Set("Expires", "0")
	req.Writer.Header().Set("Content-Type", "image/png")
	// 重载一次
	common.Instance().Reload(key)
	bytes, err := common.Instance().GetImageByte(key)
	if err != nil {
		result.Error(req, 500, "uuid失效："+err.Error())
		return
	}
	// 输出图片
	imgBase := base64.StdEncoding.EncodeToString(bytes)
	result.SuccessData(req, "验证码生成成功", imgBase)
}
